﻿using SmartRFIDSystem.dao;
using SmartRFIDSystem19.dao;
using SmartRFIDSystem19.model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartRFIDSystem19.view
{
    public partial class port : Form
    {
        public port()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            string[] prots = SerialPort.GetPortNames();
            cmbPortName.Items.AddRange(prots);
            cmbPortName.SelectedIndex = 0;
            cmbBaudRate.SelectedIndex = 0;
            cmbStopBits.SelectedIndex = 0;
            cmbDataBits.SelectedIndex = 0;
            cmbParity.SelectedIndex = 0;
            serialPort1 = new SerialPort();
            serialPort1.DataReceived += serialPort1_DataReceived;
        }

        public int flag = 0;//0时为显示账户金额  1时为可读取数据块;
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //try
            {
                Thread.Sleep(200);//每次指令的时间间隔为200ms
                int length = serialPort1.BytesToRead;
                Byte[] buff = new Byte[100];//定义接收数据的数组
                serialPort1.Read(buff, 0, length);//接收数据
                int idx, ecc_rcv = 0;//idx 数组下标  ecc_rcv校验位
                string strReceive = "";//定义接收到的卡号
                string strSourse = "";//定义接收到的数据
                string moneytext = "";//定义读出来的钱
                for (idx = 2; idx < length - 1; idx++)//计算校验
                {
                    ecc_rcv ^= buff[idx];
                }
                int money = 0;//定义读出来的钱
                if (length <= 0) return;//如果接收到的字节出问题直接返回
                if (Convert.ToByte(ecc_rcv) == buff[length - 1] && (buff[0] == 0xCD && buff[1] == 0xDC))
                {

                    if (buff[3] == 0x81)//表示接收成功
                    {
                        if (buff[4] == 0x04)//接收卡号的指令
                        {
                            for (idx = 5; idx < length - 1; idx++)//把卡号转化为字符串
                            {
                                strReceive += Convert.ToString(buff[idx], 16).PadLeft(2, '0');
                            }

                            Invoke((new Action(() =>//显示卡号文本
                            {

                                txBmcardsn.AppendText(strReceive.ToUpper().Trim());
                            })));
                        }
                        else if (buff[4] == 0x12)
                        {//读数据块
                            if (flag == 1)
                            {//把读写数据块返回的指令转化为字符串
                                for (idx = 0; idx < length; idx++)
                                {

                                    strSourse += Convert.ToString(buff[idx], 16).PadLeft(2, '0') + " ";
                                }
                                Invoke((new Action(() =>
                                {
                                    textBox1.AppendText(strSourse.ToUpper().Trim() + "\r\n");

                                })));
                            }
                            if (flag == 0)
                            {
                                for (idx = 19; idx <= 22; idx++)
                                {
                                    moneytext += Convert.ToString(buff[idx], 16).PadLeft(2, '0');
                                }
                                money = Convert.ToInt32(moneytext, 16);
                                Invoke((new Action(() =>
                                {
                                    textMoney.AppendText(1.0 * money / 100 + "");
                                })));
                            }
                        }
                        else if (buff[4] == 0x00)//接收指令成功
                        {
                            for (idx = 0; idx < length; idx++)
                            {
                                strSourse += Convert.ToString(buff[idx], 16).PadLeft(2, '0') + " ";
                            }

                            Invoke((new Action(() =>
                            {
                                textBox1.AppendText(strSourse.ToUpper().Trim() + "\r\n");
                            })));

                        }
                        

                    }

                }
            }
            // catch (Exception err)
            {
                //MessageBox.Show(err.ToString());
            }
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.PortName = cmbPortName.Text;//选择端口号
                    serialPort1.BaudRate = int.Parse(cmbBaudRate.Text);//选择波特率
                    serialPort1.DataBits = int.Parse(cmbDataBits.Text);//选择数据位
                    //选择停止位
                    if (cmbStopBits.Text == "1")
                    {
                        serialPort1.StopBits = StopBits.One;
                    }
                    else if (cmbStopBits.Text == "1.5")
                    {
                        serialPort1.StopBits = StopBits.OnePointFive;
                    }
                    else if (cmbStopBits.Text == "2")
                    {
                        serialPort1.StopBits = StopBits.Two;
                    }
                    //选择校验位
                    if (cmbParity.Text == "None")
                    {
                        serialPort1.Parity = Parity.None;
                    }
                    else if (cmbParity.Text == "Even")
                    {
                        serialPort1.Parity = Parity.Even;
                    }
                    else if (cmbParity.Text == "Odd")
                    {
                        serialPort1.Parity = Parity.Odd;
                    }
                    serialPort1.Open();//打开串口
                    MessageBox.Show("打开成功");


                }
                 catch (Exception err)
                {
                     MessageBox.Show("打开失败" + err.ToString());
                }
            }
        }

        private void btnDisConn_Click(object sender, EventArgs e)
        {

            if (serialPort1.IsOpen)
            {
                serialPort1.Close();//关闭串口
                MessageBox.Show("串口已经关闭！");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textMoney.Text = "";
            txBmcardsn.Text = "";
            try
            {
                Byte[] s = PortUtils.getCardId();
                serialPort1.Write(s, 0, 6);
                MessageBox.Show("发送成功");
            }
            catch
            {
                MessageBox.Show("串口未打开");
            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            flag = 1;
            try
            {
                int m = Convert.ToInt32(cmbSecno.Text);
                int n = Convert.ToInt32(cmbblockno.Text);
                string key = textKey.Text;
                Byte[] s = PortUtils.read(m, n, key);
                serialPort1.Write(s, 0, 15);
                MessageBox.Show("发送成功");
            }
            catch
            {
                MessageBox.Show("发送失败");
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            textMoney.Text = "";
            flag = 0;
            try
            {
                string key = textKey.Text;
                Byte[] s = PortUtils.showMoney(key);
                serialPort1.Write(s, 0, 15);
                MessageBox.Show("发送成功");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
        }


        private void button4_Click(object sender, EventArgs e)
        {
            if (textMoney.Text.Equals(""))
            {
                MessageBox.Show("请先获取余额才能充值");
                return;
            }
            try
            {

                string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "充值" + txtvalue.Text;
                UInt32 money = (UInt32)(((float.Parse(txtvalue.Text)) + (float.Parse(textMoney.Text))) * 100);//使用Uint32是因为这是钱
                Byte[] s = PortUtils.add(money, textKey.Text);
                serialPort1.Write(s, 0, 31);
                textMoney.Text = (1.0 * (int)money / 100) + "";
                log.AppendText(str + "\r\n");
                // MessageBox.Show("充值成功");
                LogDao.Recharge(txBmcardsn.Text, float.Parse(txtvalue.Text),"");
                UserDao user = new UserDao();
                float mo = (float)(1.0 *money/100);
                user.changemoney(txBmcardsn.Text,mo);
            }
            catch
            {
               // MessageBox.Show("充值失败");
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textMoney.Text.Equals(""))
            {
                MessageBox.Show("请先获取余额才能消费");
                return;
            }
            try
            {
                if ((float.Parse(textMoney.Text)) - (float.Parse(txtvalue.Text)) < 0)
                {
                    MessageBox.Show("余额不足！");
                }
                else
                {
                    string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "消费" + txtvalue.Text;
                    UInt32 money = ((UInt32)(((float.Parse(textMoney.Text)) - (float.Parse(txtvalue.Text)))) * 100);//使用Uint32是因为这是钱
                    Byte[] s = PortUtils.add(money, textKey.Text);
                    serialPort1.Write(s, 0, 31);
                    textMoney.Text = (1.0 * (int)money / 100) + "";
                    log.AppendText(str + "\r\n");
                    LogDao.Consume(txBmcardsn.Text, float.Parse(txtvalue.Text),"");
                    UserDao user = new UserDao();
                    float mo = (float)(1.0 * money / 100);
                    user.changemoney(txBmcardsn.Text, mo);
                    //MessageBox.Show("消费成功");
                }
            }
            catch
            {
              //  MessageBox.Show("消费失败");
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {

            try
            {
                string name = textName.Text;
                if (name.Equals("无"))
                {
                    MessageBox.Show("请输入姓名");
                }
                else
                {
                    string cardId = txBmcardsn.Text;
                    //MessageBox.Show(cardId);
                    string key = textKey.Text;
                    Byte[] s = PortUtils.init(key);
                    serialPort1.Write(s, 0, 31);
                    log.AppendText("卡片金额已重置\n");
                    textMoney.Text = "0";
                    UserDao user = new UserDao();
                    user.initUser(cardId, name);
                }
            }
            catch
            {

            }
        }

        private void sendTo_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void write_Click(object sender, EventArgs e)
        {
            Byte[] s = PortUtils.strTobyte(sendTo.Text);
            try
            {
                serialPort1.Write(s, 0, s.Length);
                MessageBox.Show("发送成功！");
            }catch(Exception err)
            {
                MessageBox.Show("请输入正确的指令！ "+err.ToString());
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void cmbPortName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void mysql_Click(object sender, EventArgs e)
        {
            //打开数据库管理的Web界面："http://120.27.142.116:8888/phpmyadmin/index.php?lang=zh_cn"
            //http://120.27.142.116:777/phpmyadmin_50f3a3856c548845
            System.Diagnostics.Process.Start("http://120.27.142.116:777/phpmyadmin_50f3a3856c548845");
        }

        private void textMoney_TextChanged(object sender, EventArgs e)
        {

        }

        private void log_TextChanged(object sender, EventArgs e)
        {

        }

        private void export_Click(object sender, EventArgs e)
        {
            LogDao.ExportBill();
        }
    }
}
